/**
 * 赛博侦探游戏 - 全局状态管理
 * 使用Zustand管理游戏状态
 */

import { create } from 'zustand';
import { CaseData, SuspectData, ClueData, ConversationData, GamePhase, GameSession } from '../types/game';

interface GameState {
  // 游戏数据
  currentCase: CaseData | null;
  suspects: SuspectData[];
  discoveredClues: ClueData[];
  conversationHistory: ConversationData[];
  timeRemaining: number;
  gamePhase: GamePhase;
  currentSession: GameSession | null;
  
  // 游戏操作
  startNewCase: () => Promise<void>;
  askQuestion: (question: string, suspectId: string) => Promise<void>;
  submitSolution: (solution: string) => Promise<void>;
  generatePoster: () => Promise<string>;
  updateTimeRemaining: (time: number) => void;
  setGamePhase: (phase: GamePhase) => void;
  addClue: (clue: ClueData) => void;
  getCurrentSession: () => GameSession | null;
}

/**
 * 游戏状态存储
 */
export const useGameState = create<GameState>((set, get) => ({
  // 初始状态
  currentCase: null,
  suspects: [],
  discoveredClues: [],
  conversationHistory: [],
  timeRemaining: 180, // 3分钟
  gamePhase: 'menu',
  currentSession: null,

  /**
   * 开始新案件
   */
  startNewCase: async () => {
    set({ gamePhase: 'case-gen' });
    
    try {
      // 调用Mastra AI后端API开始新游戏
      const response = await fetch('http://localhost:4111/game/start', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          difficulty: 'normal',
          theme: '办公室案件',
          suspectCount: 3
        })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.success) {
        const gameData = result.data;
        
        // 转换API数据格式为前端数据格式
        const caseData: CaseData = {
          id: gameData.case.id,
          title: gameData.case.title,
          description: gameData.case.description,
          location: gameData.case.location,
          timeOfCrime: gameData.case.timeOfCrime,
          victim: gameData.case.victim,
          murderWeapon: '未知',
          motive: '待调查',
          culpritId: 'suspect-2', // 默认设置
          difficulty: 'normal',
          createdAt: new Date()
        };
        
        // 转换嫌疑人数据
        const suspects: SuspectData[] = gameData.suspects.map((suspect: any) => ({
          id: suspect.id,
          caseId: caseData.id,
          name: suspect.name,
          personality: suspect.personality,
          background: suspect.background,
          alibi: suspect.alibi,
          secrets: [],
          isCulprit: suspect.id === 'suspect-2',
          appearance: { avatar: '', description: suspect.background },
          suspicionLevel: suspect.suspicionLevel
        }));
        
        // 转换线索数据
        const clues: ClueData[] = gameData.initialClues.map((clue: any) => ({
          id: clue.id,
          caseId: caseData.id,
          description: clue.description,
          type: clue.type,
          importance: clue.importance,
          isRevealed: true,
          relatedSuspects: []
        }));
        
        // 创建游戏会话
        const newSession: GameSession = {
          id: gameData.gameId,
          playerId: 'player-1',
          caseId: caseData.id,
          timeSpent: 0,
          score: 0,
          solved: false,
          solution: '',
          startTime: new Date(),
          conversations: [],
          discoveredClues: clues.map(c => c.id)
        };
        
        set({
          currentCase: caseData,
          suspects: suspects,
          discoveredClues: clues,
          conversationHistory: [],
          timeRemaining: 180,
          gamePhase: 'investigation',
          currentSession: newSession
        });
        
        return;
      } else {
          throw new Error(result.message || '开始游戏失败');
        }
      
    } catch (error) {
      console.error('开始游戏失败:', error);
      
      // 如果API调用失败，使用本地模拟数据作为后备
      console.log('使用本地模拟数据');
      
      // 临时模拟数据
      const mockCase: CaseData = {
        id: `case-${Date.now()}`,
        title: '办公室咖啡毒杀案',
        description: '在科技公司办公室发现一名员工死于咖啡中毒',
        location: '科技公司办公室',
        timeOfCrime: '上午10:30',
        victim: '张经理',
        murderWeapon: '氰化物',
        motive: '升职竞争',
        culpritId: 'suspect-2',
        difficulty: 'normal',
        createdAt: new Date()
      };
      
      const mockSuspects: SuspectData[] = [
        {
          id: 'suspect-1',
          caseId: mockCase.id,
          name: '李助理',
          personality: '谨慎内向',
          background: '新入职员工',
          alibi: '在会议室开会',
          secrets: ['暗恋受害者'],
          isCulprit: false,
          appearance: { avatar: '', description: '年轻女性，戴眼镜' },
          suspicionLevel: 3
        },
        {
          id: 'suspect-2',
          caseId: mockCase.id,
          name: '王同事',
          personality: '野心勃勃',
          background: '竞争对手',
          alibi: '在洗手间',
          secrets: ['伪造了不在场证明'],
          isCulprit: true,
          appearance: { avatar: '', description: '中年男性，西装革履' },
          suspicionLevel: 7
        },
        {
          id: 'suspect-3',
          caseId: mockCase.id,
          name: '陈清洁工',
          personality: '老实本分',
          background: '公司清洁工',
          alibi: '在打扫其他楼层',
          secrets: ['看到了可疑人物'],
          isCulprit: false,
          appearance: { avatar: '', description: '年长男性，朴素着装' },
          suspicionLevel: 2
        }
      ];
      
      const mockClues: ClueData[] = [
        {
          id: 'clue-1',
          caseId: mockCase.id,
          description: '咖啡杯上有指纹',
          type: 'physical',
          importance: 4,
          isRevealed: true,
          relatedSuspects: ['suspect-2']
        },
        {
          id: 'clue-2',
          caseId: mockCase.id,
          description: '监控显示有人接近咖啡机',
          type: 'digital',
          importance: 5,
          isRevealed: false,
          relatedSuspects: ['suspect-2']
        }
      ];
      
      // 创建游戏会话
      const newSession: GameSession = {
        id: `session-${Date.now()}`,
        playerId: 'player-1',
        caseId: mockCase.id,
        timeSpent: 0,
        score: 0,
        solved: false,
        solution: '',
        startTime: new Date(),
        conversations: [],
        discoveredClues: mockClues.filter(c => c.isRevealed).map(c => c.id)
      };
      
      set({
        currentCase: mockCase,
        suspects: mockSuspects,
        discoveredClues: mockClues.filter(c => c.isRevealed),
        conversationHistory: [],
        timeRemaining: 180,
        gamePhase: 'investigation',
        currentSession: newSession
      });
    }
  },

  /**
   * 向嫌疑人提问
   */
  askQuestion: async (question: string, suspectId: string) => {
    try {
      // 调用Mastra AI后端API进行嫌疑人对话
      const response = await fetch('http://localhost:4111/game/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          gameId: get().currentSession?.id || 'default-game',
          suspectId,
          question,
          conversationHistory: get().conversationHistory,
          timeRemaining: get().timeRemaining,
          discoveredClues: get().discoveredClues.map(c => c.id)
        })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.success) {
        const apiResponse = result.data;
        
        const conversation: ConversationData = {
          id: `conv-${Date.now()}`,
          gameSessionId: get().currentSession?.id || '',
          suspectId,
          question,
          response: apiResponse.response,
          timestamp: new Date(),
          suspicionLevel: apiResponse.suspicionLevel,
          cluesRevealed: apiResponse.newClues || []
        };
        
        // 更新对话历史
        set(state => ({
          conversationHistory: [...state.conversationHistory, conversation]
        }));
        
        // 如果有新线索，添加到已发现线索中
        if (apiResponse.newClues && apiResponse.newClues.length > 0) {
          set(state => ({
            discoveredClues: [...state.discoveredClues, ...apiResponse.newClues]
          }));
        }
      } else {
        throw new Error(result.message || '对话失败');
      }
      
    } catch (error) {
      console.error('提问失败:', error);
      
      // 如果API调用失败，使用本地模拟数据作为后备
      const suspect = get().suspects.find(s => s.id === suspectId);
      const mockResponse = {
        answer: `${suspect?.name}: 抱歉，我现在无法回答这个问题。`,
        suspicionLevel: Math.floor(Math.random() * 10) + 1
      };
      
      const conversation: ConversationData = {
        id: `conv-${Date.now()}`,
        gameSessionId: get().currentSession?.id || '',
        suspectId,
        question,
        response: mockResponse.answer,
        timestamp: new Date(),
        suspicionLevel: mockResponse.suspicionLevel,
        cluesRevealed: []
      };
      
      set(state => ({
        conversationHistory: [...state.conversationHistory, conversation]
      }));
    }
  },

  /**
   * 提交推理结果
   */
  submitSolution: async (solution: string) => {
    const session = get().currentSession;
    if (!session) return;
    
    // TODO: 调用AI评判Agent评估答案
    const isCorrect = solution.includes('王同事'); // 临时判断逻辑
    
    const timeSpent = 180 - get().timeRemaining;
    const score = isCorrect ? Math.max(100 - timeSpent, 10) : 0;
    
    set(state => ({
      currentSession: state.currentSession ? {
        ...state.currentSession,
        solved: isCorrect,
        solution,
        score,
        timeSpent,
        endTime: new Date()
      } : null,
      gamePhase: 'reveal'
    }));
  },

  /**
   * 生成案情回顾海报
   */
  generatePoster: async () => {
    // TODO: 实现海报生成逻辑
    return '-poster-data';
  },

  /**
   * 更新剩余时间
   */
  updateTimeRemaining: (time: number) => {
    set({ timeRemaining: time });
    
    // 时间到了自动结束游戏
    if (time <= 0) {
      set({ gamePhase: 'reveal' });
    }
  },

  /**
   * 设置游戏阶段
   */
  setGamePhase: (phase: GamePhase) => {
    set({ gamePhase: phase });
  },

  /**
   * 添加新线索
   */
  addClue: (clue: ClueData) => {
    set(state => ({
      discoveredClues: [...state.discoveredClues, clue]
    }));
  },

  /**
   * 获取当前游戏会话
   */
  getCurrentSession: () => {
    return get().currentSession;
  }
}));

/**
 * 导出游戏状态钩子
 */
export default useGameState;